<?php

/**
 * 佣金计算类
 * 
 * @file CommissionCalculate.php
 * @author yff
 * @date 2018-8-14
 */

namespace App\Http\ManagerApi\Classes;

use App\Http\ManagerApi\Models\PlatformSetting;
use App\Http\ManagerApi\Models\User as PlatformUser;
use App\Http\ManagerApi\Models\TeamMember;
use Illuminate\Support\Facades\DB;
use App\Http\ManagerApi\Models\UserIntegralLog;

class CommissionCalculate
{
    // 当前推荐人对象
    private $current_user;

    // 当前所获佣金
    private $current_commission = 0;

    // 平台设置对象
    private $setting;

    /**
     * 构造方法
     * @param int $super_uid 推荐人uid
     */
    public function __construct(int $super_uid)
    {
        if (!$super_uid) {
            die('缺少参数！');
        }

        $this->current_user = PlatformUser::findOrFail($super_uid);

        $this->setting = $setting = PlatformSetting::firstOrFail();

        // 直属上级佣金
        $this->current_commission = (int)(($setting->register_fee - (int)$setting->register_fee * $setting->service_charge_rate) * $setting->commission_rate);
    }

    /**
     * 递归计算上级获取佣金
     */
    public function calculateCommission()
    {
        DB::beginTransaction();

        // 获取下级人数
        $sub_number = $this->getSubNumber();

        // 获取上级对象
        $super = $this->getSuper();
        
        // 返利
        $rebate = 0;

        // 判断是否已达获取返利条件
        if ($sub_number >= $this->setting->sub_max_number && isset($super)) {

            // 上级返利
            $rebate = (int)((int)($this->current_commission * $this->setting->commission_rate) * $this->setting->sub_rebate_rate);
        }
        
        // 更新当前用户积分、总积分
        $this->current_user->total_integral += ($this->current_commission + $rebate);
        $this->current_user->integral += ($this->current_commission + $rebate);
        $res = $this->current_user->save();

        // 插入积分记录表
        $create = [
            'uid' => $this->current_user->id,
            'changed_integral' => $this->current_commission + $rebate,
            'current_integral' => $this->current_user->integral,
            'type' => 1,
            'is_finished' => 1,
            'desc' => '佣金'
        ];
        $log = UserIntegralLog::create($create);

        if (!$res && !$log) {
            DB::rollback();
        }

        if (isset($super)) {

            $this->current_commission = (int)($this->current_commission * $this->setting->commission_rate);

            $this->current_user = $super;

            // 递归
            $this->calculateCommission();
        }

        DB::commit();
    }

    /**
     * 获取当前用户下级人数
     */
    public function getSubNumber()
    {
        return TeamMember::where('uid', $this->current_user->id)->count();
    }

    /**
     * 获取当前用户上级
     */
    public function getSuper()
    {
        $sup_uid = TeamMember::where('sub_uid', $this->current_user->id)->value('uid');

        return PlatformUser::find($sup_uid);
    }
}